import AdManager, { AdType, IAdConfig } from "./AdManager";
import EngineUtil from "./EngineUtil";
import NativeConsts from "./NativeConsts";

const { ccclass, property } = cc._decorator;
@ccclass
export default class NativeUtils {
    static _mapNativeCallback = {};
    static _lastKeyBackTime = null;

    static registerCallback(e, t) {
        console.log("注册" + e + "监听");
        window[e] = t;
    }
    static unregisterCallback(e) {
        delete this._mapNativeCallback[e];
    }
    static cocosInit(e) {
        this.unregisterCallback("showExitDialog");
        this.unregisterCallback("userInfo");
        this.unregisterCallback("wxLoginSuccess");
        this.unregisterCallback("nativeAdShow");
        this.unregisterCallback("setAuditMode");

        this.registerCallback("nativeAdonload", () => { });
        this.registerCallback("showExitDialog", this.onKeyBackCallback);
        this.registerCallback("userInfo", e);
        this.registerCallback("wxLoginSuccess", e);
        this.registerCallback("nativeAdShow", () => { })
        this.registerCallback("restartGame", () => {
            cc.game.restart();
        });
        this.registerCallback("setAuditMode", () => {
            cc.game.restart();
        });

        this.unregisterCallback("setAttributeSource");
        this.registerCallback("setAttributeSource", (attributeSource) => {
            console.log("attributeSource", attributeSource);
            cc.game.restart();
        });

        window["nativeAdonload"] = () => { };
        window["interstitialAdOnLoad"] = () => { };

        AdManager.getAdIDByType(AdType.NATIVE).then(val => {
            this.jsbCall('nativeAdLoad', '(Ljava/lang/String;)V', JSON.stringify({
                "adId": val,
                "adPlacement": 0
            }))
        })

        AdManager.getAdIDByType(AdType.INTERSTITIAL).then(val => {
            this.jsbCall('newInterstitialAdLoad', '(Ljava/lang/String;)V', JSON.stringify({
                "adId": val,
                "adPlacement": 0
            }));
        })

    }

    static onKeyBackCallback() {
        let t = new Date().getTime();
        if (!this._lastKeyBackTime || t - this._lastKeyBackTime > 1000) {
            this._lastKeyBackTime = t;
            EngineUtil.showManageViewToast("再按一次返回退出应用");
        } else cc.game.end();
    }

    /**
     * 调用支付宝登陆
     */
    static alipayLogin(cb) {
        this.registerCallback("userInfo", cb);
        this.jsbCall('alipayLogin', '()V');
    }

    private get adManager() {
        return AdManager.getAdConfig();
    }
    static cocosInitCallback(e) {
        let t = JSON.parse(e);
        if (this._mapNativeCallback[NativeConsts.appInfo]) {
            this._mapNativeCallback[NativeConsts.appInfo](t);
            this._mapNativeCallback[NativeConsts.appInfo] = null;
            delete this._mapNativeCallback[NativeConsts.appInfo];
        }
    }

    static wechatLogin(e) {
        // this._mapNativeCallback[NativeConsts.wechartLogin] = e;
        // if (cc.sys.isBrowser) this.wechartLoginCallback(DataManager.Instance.getHttpHeaderMessage().accessKey); else {
        //     NativeConsts.isAndroid && jsb.reflection.callStaticMethod(NativeConsts.NativeClassPath, NativeConsts.wechartLogin, "()V");
        //     NativeConsts.isIOS && jsb.reflection.callStaticMethod(NativeConsts.NativeClassPath, NativeConsts.wechartLogin, "{}");
        // }
        console.log('调用wxLogin');
        return new Promise((resolve) => {
            this.jsbCall('wxLogin', '()V')
        })
    }

    static visitorLogin() {
        console.log('调用visitorLogin');
        return new Promise((resolve) => {
            this.jsbCall('visitorLogin', '()V')
        })
    }

    static wechartLoginCallback(e) {
        if (this._mapNativeCallback[NativeConsts.wechartLogin]) {
            this._mapNativeCallback[NativeConsts.wechartLogin](e);
            this._mapNativeCallback[NativeConsts.wechartLogin] = null;
            delete this._mapNativeCallback[NativeConsts.wechartLogin];
        }
    }
    static shareWeChartCallback(e) {
        let t = JSON.parse(e);
        if (this._mapNativeCallback[NativeConsts.shareWeChat]) {
            this._mapNativeCallback[NativeConsts.shareWeChat](t.result);
            this._mapNativeCallback[NativeConsts.shareWeChat] = null;
            delete this._mapNativeCallback[NativeConsts.shareWeChat];
        }
    }

    static _rewardedVideoAdTimer: number = -1;
    static showVideoAd(place, cb) {
        if (place['posId']) {
            place = place['posId'];
        }
        console.log('播放激励视频', place);
        AdManager.getAdIDByPlace(place, AdType.MOTIVATIONAL_VIDEO).then(adId => {
            console.log("请求广告", place)
            // this._mapNativeCallback[NativeConsts.showVideoAD] = cb;
            if (cc.sys.isBrowser) {
                // this.showVideoAdCallback(JSON.stringify({
                //     result: "success"
                // }));
                console.log("假装广告播放完了");
                cb && cb("success");
            } else {
                this._rewardedVideoAdTimer = setTimeout(() => {
                    cb && cb("fail");
                    // this.hideLoading();
                }, 5000);
                this.showLoading();
                setTimeout(() => {
                    this.hideLoading();
                }, 3000);
                this.rewardedVideoAdLoad(place, () => {
                    window["rewardedVideoAdClose"] = (res) => {
                        this.hideLoading();
                        console.log('rewardedVideoAdClose' + res.isEnded)
                        cb && cb(res.isEnded ? "success" : 'fail');

                        // this.jsbCall('rewardedVideoAdLoad', '(Ljava/lang/String;)V', JSON.stringify({
                        //     "adId": adId,
                        //     "yardLevel": CityLevelManager.Instance.getCityLevel(),
                        //     "adPlacement": place['posName'] ? place['posName'] : place
                        // }));
                    }

                    window['rewardedVideoAdShowFailed'] = null;
                    window['rewardedVideoAdShowFailed'] = (data) => {
                        // uiManager.instance.showTips('广告展示超时');
                        cb && cb("fail");
                        this.hideLoading();
                    }
                    this.hideLoading();
                    clearTimeout(this._rewardedVideoAdTimer);
                    // console.log("请求广告1", place)
                    // this.jsbCall('rewardedVideoAdShow', '(Ljava/lang/String;)V', adId)
                    // console.log('rewardedVideoAdShow 广告ID： ' + adId, place);

                    // 调用函数来累加视频观看次数
                    this.incrementVideoViews();
                });
            }
        })
    }

    static incrementVideoViews() {
        // 检查本地存储中是否存在视频观看次数
        let videoViews = parseInt(localStorage.getItem('videoViews'));

        // 如果视频观看次数不存在，则初始化为0
        if (!videoViews) {
            videoViews = 0;
        }

        // 将视频观看次数加1
        videoViews++;

        this.userSet({ "total_ad_num": videoViews });
        // 更新本地存储中的视频观看次数
        localStorage.setItem('videoViews', videoViews + "");
    }

    // static showVideoAdCallback(e) {
    //     let t = JSON.parse(e).result;
    //     if (this._mapNativeCallback[NativeConsts.showVideoAD]) {
    //         this._mapNativeCallback[NativeConsts.showVideoAD](t);
    //         this._mapNativeCallback[NativeConsts.showVideoAD] = null;
    //         delete this._mapNativeCallback[NativeConsts.showVideoAD];
    //         if ("success" === t) {
    //             let e = this._mapNativeCallback[NativeConsts.sevenCashCheck];
    //             e && e();
    //         }
    //     }
    // }

    static showAdImage(place) {
        AdManager.getAdIDByPlace(place, AdType.NATIVE).then((adId: number) => {
            window['nativeAdOnLoad'] = (info) => {
                // cb(true);
                console.log('原生广告加载完成' + adId);
                AdManager.getConfigByAID(adId).then(data => {
                    this.jsbCall('nativeAdShow', '(Ljava/lang/String;)V', adId);
                })
                this.nativeAdLoad(place);
                window['nativeAdOnLoad'] = () => { }
                console.log('nativeAdOnLoad 广告ID： ' + adId, place);
            }
            this.nativeAdLoad(place);
        })

        for (let i = 0; i < this._adCloseTimeout.length; i++) {
            clearTimeout(this._adCloseTimeout[i]);
        }
        this._adCloseTimeout = [];
    }
    static showAdImageCallback(e) {
        console.log("========native调用 cocos=========showAdImageCallback=======", e);
        let t = JSON.parse(e).result;
        if (this._mapNativeCallback[NativeConsts.showAdImage]) {
            this._mapNativeCallback[NativeConsts.showAdImage](t);
            this._mapNativeCallback[NativeConsts.showAdImage] = null;
            delete this._mapNativeCallback[NativeConsts.showAdImage];
        }
    }

    static _adCloseTimeout: number[] = [];
    static hideAdImage() {
        if (cc.sys.isBrowser) {
            return;
        }
        // window['nativeAdOnLoad'] = null;
        // this.jsbCall('nativeAdClose', '()V');

        // for (let i = 0; i < 50; i++) {
        //     let d = setTimeout(() => {
        //         this.jsbCall('nativeAdClose', '()V')
        //         this.jsbCall('bannerAdClose', '()V');
        //     }, i * 200)
        //     this._adCloseTimeout.push(d);
        // }
    }
    static showBanner(place) {
        AdManager.getAdIDByPlace(place, AdType.BANNER).then(id => {
            this.jsbCall('bannerAdLoad', '(Ljava/lang/String;)V', JSON.stringify({
                "adId": id,
                "adPlacement": place['posName'] ? place['posName'] : place
            }))
            for (let i = 0; i < this._adCloseTimeout.length; i++) {
                clearTimeout(this._adCloseTimeout[i]);
            }
            this._adCloseTimeout = [];
        });
    }
    static showBannerCallback(e) {
        console.log("========native调用 cocos=========showAdBannerCallback=======", e);
        let t = JSON.parse(e).result;
        if (this._mapNativeCallback[NativeConsts.showBanner]) {
            this._mapNativeCallback[NativeConsts.showBanner](t);
            this._mapNativeCallback[NativeConsts.showBanner] = null;
            delete this._mapNativeCallback[NativeConsts.showBanner];
        }
    }
    static hideBanner() {
        if (cc.sys.isBrowser) {
            return;
        }
        // this.jsbCall('bannerAdClose', '()V');

        // for (let i = 0; i < 50; i++) {
        //     let d = setTimeout(() => {
        //         this.jsbCall('nativeAdClose', '()V')
        //         this.jsbCall('bannerAdClose', '()V');
        //     }, i * 200)
        //     this._adCloseTimeout.push(d);
        // }
    }

    static _requestIntervalObj = {};
    static showScreenAds(place, cb, isOpen = true) {
        if (cc.sys.isBrowser) this.screenAdsCallBack(JSON.stringify({ result: "success" }));

        // AdManager.getAdIDByPlace(place, AdType.INTERSTITIAL).then((adId: number) => {
        //     if (adId == 0) {
        //         console.log('插屏广告错误，找不到adID');
        //         return;
        //     }

        //     AdManager.getConfigByAID(adId).then((data) => {
        //         if (this._requestIntervalObj[adId] && Date.now() - this._requestIntervalObj[adId] < data['requestInterval'] * 1000) {
        //             console.log('nativeAdOnLoad未到间隔时间', Date.now() - this._requestIntervalObj[adId]);
        //             return;
        //         }
        //         setTimeout(() => {
        //             this.jsbCall('newInterstitialAdLoad', '(Ljava/lang/String;)V', JSON.stringify({
        //                 "adId": adId,
        //                 "adPlacement": place
        //             }));
        //             this._requestIntervalObj[adId] = Date.now();
        //         }, isOpen ? (data['openPageDelayInterval'] || 9999) * 1000 : (data['closePageDelayInterval'] || 9999) * 1000);

        //         window['interstitialAdOnLoad'] = (info) => {
        //             cb && cb();
        //             console.log('原生广告加载完成' + adId);
        //             this._requestIntervalObj[adId] = Date.now();
        //             this.jsbCall('interstitialAdShow', '(Ljava/lang/String;)V', adId + '');
        //             this.jsbCall('newInterstitialAdLoad', '(Ljava/lang/String;)V', JSON.stringify({
        //                 "adId": adId,
        //                 "adPlacement": place
        //             }));
        //             window['interstitialAdOnLoad'] = () => { };
        //             console.log('interstitialAdShow 广告ID： ' + adId, place);
        //         };
        //     });
        // });
    }
    static screenAdsCallBack(e) {
        let t = JSON.parse(e).result;
        if (this._mapNativeCallback[NativeConsts.screenAds]) {
            this._mapNativeCallback[NativeConsts.screenAds](t);
            this._mapNativeCallback[NativeConsts.screenAds] = null;
            delete this._mapNativeCallback[NativeConsts.screenAds];
        }
    }


    static lastCallTime = 0;
    static openWebView(url, cb = null) {
        const currentTime = Date.now();
        const timeInterval = 1000; // 指定的时间间隔，单位为毫秒

        if (currentTime - this.lastCallTime > timeInterval) {
            this.lastCallTime = currentTime;

            if (!cc.sys.isBrowser) {
                this.jsbCall('openUrl', '(Ljava/lang/String;)V', url);
            }
        }
    }

    static jsbCall(key, type, ...parm) {
        // try {
        //     if (key.indexOf('Close') == -1) {
        //         console.log('请求andorid ', key, type, ...parm);
        //     }
        //     return jsb.reflection.callStaticMethod("com/coolidiom/king/JsAndroidTrans/CocosCallAndroid", key, type, ...parm);
        // } catch (error) {
        //     console.error('调用jsbcall出错' + key);
        // }
    }

    static httpPost(url, pram, cb, body = "") {
        this.jsbCall('post', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V', url, body, pram, cb);
    }

    static num = 0;
    static nativePost(url, params, callback, thisObj, errCb = null, body = null) {
        let tempNum = this.num;
        this.num++;
        window['onreadystatechange' + tempNum] = (data) => {
            console.log('------------');
            // try {
            console.log('接口返回', url, data.code, data.errorMsg, data.data);
            console.log('------------');
            // if (data.code == -1) {
            //     // uiManager.instance.showTips(data.errorMsg);
            //     setTimeout(() => {
            //         this.nativePost(url, params, callback, thisObj, errCb);//如果请求错误1s后重新请求
            //     }, 1000);
            //     return;
            // }
            window['onreadystatechange' + tempNum] = null;
            // data = data.replace(/\\\\\\\"/g, '"');
            // data = data.replace(/\\\"/g, '"');

            // console.log(111111111 + data);
            let rsp = data;
            data.result = JSON.parse(data.data);
            if (rsp.code == 0) {
                callback.apply(thisObj, [rsp]);
            } else {
                errCb && errCb.apply(thisObj, [rsp]);
            }
            // } catch (error) {
            //     console.error('------------');
            //     console.error("接口出错", url);
            //     console.error(JSON.stringify(error));
            //     console.error('------------');
            // }
        }
        this.httpPost(url, JSON.stringify(params), 'onreadystatechange' + tempNum, body);
    }

    static async getInterstitialTypeByPlace(place) {
        return new Promise((resolve) => {
            AdManager.getAdConfig().then((adConfigs: IAdConfig[]) => {
                const interstitialType = adConfigs.filter((data) => {
                    return data.adPlacement.indexOf(place) != -1;
                })[0]?.interstitialType;
                resolve(interstitialType || '');
            });
        })
    }

    /**
     * 加载激励视频
     * @param cb
     */
    static async rewardedVideoAdLoad(place, cb, tip = false) {
        if (!this.isNative) {
            cb && cb(true);
            return;
        }
        if (this.isNative) {
            AdManager.getAdTypeByPlace(place).then(type => {
                window['rewardedVideoAdOnLoad'] = () => {
                    console.log('广告加载完成');
                    cb && cb();
                    window['rewardedVideoAdOnLoad'] = () => { }
                }
                AdManager.getAdIDByPlace(place, AdType.MOTIVATIONAL_VIDEO).then(id => {
                    this.jsbCall('rewardedVideoAdLoad', '(Ljava/lang/String;)V', JSON.stringify({
                        "adId": id,
                        "adPlacement": place['posName'] ? place['posName'] : place
                    }))
                })

                window['rewardedVideoAdLoadFailed'] = null;
                window['rewardedVideoAdLoadFailed'] = (data) => {
                    // UIManager.show_toast({
                    //     text: "系统已为您跳过广告"
                    // });
                    cb && cb(false);
                }
            })
        }
    }


    /**
    * 加载原生广告
    * @param cbc
    */
    static nativeAdLoad(place) {
        AdManager.getAdIDByPlace(place, AdType.NATIVE).then(id => {
            this.jsbCall('nativeAdLoad', '(Ljava/lang/String;)V', JSON.stringify({
                "adId": id,
                "adPlacement": place['posName'] ? place['posName'] : place
            }))
        });
    }

    /**
    * 开屏id
    */
    static setSplashAdId() {
        AdManager.getAdIDByPlace(31, AdType.OPEN_SCREEN).then((adId) => {
            console.log("开屏广告id", adId);
            this.jsbCall('setSplashAdId', '(Ljava/lang/String;)V', JSON.stringify({
                "adId": adId,
                "adPlacement": 31
            }));
        });
    }

    static _isDebugger;
    static isDebugMode(): boolean {
        if (!this.isNative) {
            return false;
        }
        if (this._isDebugger !== undefined) {
            return this._isDebugger;
        }
        this._isDebugger = this.jsbCall('isDebugMode', '()Z');
        return this._isDebugger;
    }

    static report(key, val) {
        this.jsbCall('report', '(Ljava/lang/String;Ljava/lang/String;)V', key, JSON.stringify(val));
        console.log("上报事件", key, JSON.stringify(val));
    }

    static get isNative(): boolean {
        return cc.sys.isNative;
    }

    static _showLoadingTimer = -1;
    static showLoading() {

        // this.throttle(() => {
        //     this._showLoadingTimer = setTimeout(()=>{
        //         this.jsbCall('showLoading', '()V');
        //     },1000)
        // }, 1000);
    }

    static throttle(func: Function, wait: number): Function {
        let timeout: ReturnType<typeof setTimeout> | null = null;
        return function (this: any, ...args: any[]) {
            if (!timeout) {
                timeout = setTimeout(() => {
                    func.apply(this, args);
                    timeout = null;
                }, wait);
            }
        }
    }

    static hideLoading() {
        clearTimeout(this._showLoadingTimer);
        this.jsbCall('hideLoading', '()V');
    }

    // reportEvent 的枚举 public final static int EVENT_TYPE_WITHDRAWAL_NEW_USER = 100118; //激活_新人提现
    // public final static int EVENT_TYPE_WITHDRAWAL_YUAN_BAO = 100119; //激活_元宝提现
    // public final static int EVENT_TYPE_ALIPAY_RTA = 100120; //激活_支付宝rta接口返回
    // public final static int EVENT_TYPE_WITHDRAWAL_ALIPAY = 100121; //激活_支付宝提现
    // public final static int EVENT_TYPE_ALIPAY_RTA_NEW = 100122; //激活_支付宝rta_新用户
    // public final static int EVENT_TYPE_ALIPAY_RTA_ACTIVE = 100123; //激活_支付宝rta_沉流用户
    // public final static int EVENT_TYPE_ALIPAY_RTA_NULL = 100124; //激活_支付宝rta_空
    static attributionReport(key, val) {
        this.jsbCall('report', '(ILjava/lang/String;)V', key, val);
        console.log("reportEvent", Number(key), String(val));
    }

    static getChannelType(): number {
        //穿山甲12
        return this.jsbCall('getChannelType', '()I');
    }

    static showAppInfo(): number {
        return this.jsbCall('showAppInfo', '()V');
    }

    static logout(): void {
        // SoundManager.pauseAll();
        return this.jsbCall('logout', '()V');
    }

    static gameLoadSuccess() {
        if (!this.isNative) {
            return;
        }
        if (this.isNative) {
            this.jsbCall('gameLoadSuccess', '()V')
        }
    }

    // 打开隐私政策
    static openPrivacyUrl() {
        if (!this.isNative) {
            return;
        }
        if (this.isNative) {
            this.jsbCall('openPrivacyUrl', '()V')
        }
    }

    // 打开用户协议
    static openContractUrl() {
        if (!this.isNative) {
            return;
        }
        if (this.isNative) {
            this.jsbCall('openContractUrl', '()V')
        }
    }

    //通知安卓
    static openFeedbackUrl() {
        if (!this.isNative) {
            return;
        }
        if (this.isNative) {
            this.jsbCall('openFeedbackUrl', '()V')
        }
    }

    static setVibrator(e = 300) {
        this.jsbCall('vibrate', '(I)V')
    }

    static report2(key, val) {
        this.jsbCall('track', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V', key, JSON.stringify(val), JSON.stringify({}));
        console.log("上报事件", key, JSON.stringify(val));
    }

    /**
     * 设置用户数据
     * @param userProperties 用户数据参数
     */
    static userSet(val) {
        this.jsbCall('userSet', '(Ljava/lang/String;)V', JSON.stringify(val));
        console.log("上报用户信息", JSON.stringify(val));
    }

}
